<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            display: flex;
            height: 100vh;
        }

        canvas {
            margin: auto;
            border: thin solid #ccc;
        }
    </style>
</head>

<body>
    <canvas id='canvas' width='800' height='520'>
        Canvas not supported
    </canvas>
    <script>
        const canvas = document.getElementById('canvas')
        const ctx = canvas.getContext('2d')
        ctx.lineWidth = 2;
        ctx.strokeStyle = 'green'
        ctx.lineJoin="round";
        let oX, oY, draw = false;
        // x,y坐标转换为canvas内的坐标
        function windowTocanvas(x, y) {
            const canvasBox = canvas.getBoundingClientRect();
            return {
                x: x - canvasBox.left * (canvas.width / canvasBox.width),
                y: y - canvasBox.top * (canvas.height / canvasBox.height)
            }
        }
        canvas.addEventListener('mousedown', function (e) {
            const loc = windowTocanvas(e.clientX, e.clientY)
            oX = loc.x;
            oY = loc.y
            draw = !draw
            ctx.beginPath();
            ctx.moveTo(oX, oY)
        })
        canvas.addEventListener('mousemove', function (e) {
            if (!draw) return
            const loc = windowTocanvas(e.clientX, e.clientY)
            // ctx.beginPath();
            // ctx.moveTo(oX, oY)
            ctx.lineTo(loc.x, loc.y)
            ctx.stroke();
            // oX = loc.x;
            // oY = loc.y
        })
        
    </script>
</body>

</html>